import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from '@/router/routes'
import store from '@/store'

Vue.use(VueRouter)

let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function(location,resolved,rejected){
    if(resolved === undefined && rejected === undefined){
       return originPush.call(this,location).catch(()=>{})
    }else{
        return originPush.call(this,location,resolved,rejected)
    }
}
VueRouter.prototype.replace = function(location,resolved,rejected){
    if(!resolved || !rejected){
        return originReplace.call(this,location).catch(()=>{})
    }else{
        return originReplace.call(location,resolved,rejected)
    }
}

const router = new VueRouter({
    mode:'history',
    routes,
    scrollBehavior () {
        return { y: 0 }
      }
})

router.beforeEach(async (to, from, next) => {

    let token = store.state.user.token  
    let userInfo = store.state.user.userInfo
  
    if(token){
      if(to.path === '/login'){
        next('/')
      }else{
        if(userInfo.name){
          next()
        }else{
          try {
            await store.dispatch('getUserInfo')
            next()
          } catch (error) {
            store.dispatch('clearToken') 
            next('/login')
          }
        }
      }
    }else{
      if(to.path.startsWith('/shopcart') || to.path.startsWith('/admin')){
        console.log(to.path)
        next('/login?redirect=' + to.path)
      }else{
        next()
      }
    }
})



export default router